<template>
  <div>
    <el-table :data="categories" border style="width: 100%;">
      <!-- 显示分类名字 -->
      <el-table-column prop="name" label="名字" align="center"></el-table-column>

      <!-- 操作列：删除 -->
      <el-table-column label="删除" align="center">
        <template v-slot:default="{ row }">
          <el-button type="danger" @click="deleteCategory(row.id)">删除</el-button>
        </template>
      </el-table-column>

      <!-- 操作列：修改 -->
      <el-table-column label="修改" align="center">
        <template v-slot:default="{ row }">
          <el-button type="primary" @click="editCategory(row)">修改</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 增添按钮，放在表格最后 -->
    <div class="add-button">
      <el-button type="success" @click="showAddDialog">增添分类</el-button>
    </div>

    <!-- 编辑分类弹窗 -->
    <el-dialog title="修改分类" v-model="dialogVisible" width="400px">
      <el-form :model="currentCategory" ref="form" label-width="80px">
        <el-form-item label="分类名称" :rules="[ { required: true, message: '分类名称不能为空', trigger: 'blur' } ]">
          <el-input v-model="currentCategory.name" placeholder="请输入分类名称" />
        </el-form-item>
      </el-form>
      <template v-slot:footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveCategory">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import { fetchCategories } from '@/api/category';

export default {
  name: 'CategoryMenu',
  emits: ['category-selected'],
  setup(props, { emit }) {
    const categories = ref([]);  // 存储分类数据
    const dialogVisible = ref(false);  // 控制弹窗显示与否
    const currentCategory = ref({ id: null, name: '' });  // 当前编辑的分类

    // 获取分类列表
    const getCategories = async () => {
      try {
        const categoriesData = await fetchCategories();
        categories.value = categoriesData;  // 更新分类数据
        console.log('Categories loaded:', categories.value);
      } catch (error) {
        console.error('Error fetching categories in CategoryMenu:', error.message);
      }
    };

    // 删除分类
    const deleteCategory = async (categoryId) => {
      if (!categoryId) {
        console.error("Invalid category ID");
        return;  // 如果categoryId无效则返回
      }
      try {
        await axios.delete(`http://192.168.239.53:8082/category/${categoryId}`);
        // 删除成功后更新本地分类列表
        categories.value = categories.value.filter(
          (category) => category.id !== categoryId
        );
        console.log(`Category with ID ${categoryId} deleted successfully.`);
      } catch (error) {
        console.error(`Error deleting category with ID ${categoryId}:`, error);
      }
    };

    // 编辑分类
    const editCategory = (category) => {
      currentCategory.value = { ...category };  // 设置编辑的数据
      dialogVisible.value = true;  // 显示弹窗
    };

    // 保存分类（修改或新增）
    const saveCategory = async () => {
      try {
        let response;
        console.log("Saving category:", currentCategory.value);  // 调试输出，查看保存的内容

        if (currentCategory.value.id) {
          // 更新已存在的分类
          response = await axios.put(`http://192.168.239.53:8082/category/${currentCategory.value.id}`, currentCategory.value);
          console.log("Response after PUT:", response.data);  // 查看后端返回的数据

          const index = categories.value.findIndex(category => category.id === currentCategory.value.id);
          if (index !== -1) {
            categories.value[index] = { ...currentCategory.value };  // 更新数组中的分类
            console.log("Updated categories:", categories.value);  // 查看更新后的分类列表
          }
        } else {
          // 添加新分类
          response = await axios.post('http://192.168.239.53:8082/category', currentCategory.value);
          console.log("Response after POST:", response.data);  // 查看后端返回的数据
          categories.value.push(response.data);  // 将新分类添加到列表中
        }
        getCategories();
        dialogVisible.value = false;  // 关闭弹窗
        console.log('Category saved successfully.');
      } catch (error) {
        console.error('Error saving category:', error);
      }
    };

    // 显示添加分类弹窗
    const showAddDialog = () => {
      currentCategory.value = { id: null, name: '' };  // 清空当前分类数据
      dialogVisible.value = true;  // 显示弹窗
    };

    // 在组件挂载时获取分类数据
    onMounted(() => {
      getCategories();
    });

    return { categories, dialogVisible, currentCategory, deleteCategory, editCategory, saveCategory, showAddDialog };
  },
};
</script>

<style scoped>
.add-button {
  position: absolute;
  bottom: 20px;
  right: 20px;
}
</style>
